package test;

import test.exception.ValidateException;
import test.kit.StringKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2016/10/6.
 */
public abstract class BaseValidate {
    HttpServletRequest request;
    HttpServletResponse response;
    private String errorMsg = "-1001";

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    /**
     * 验证请求域信息
     */
    public abstract void validate();

    /**
     * 处理异常
     * @param e
     */
    public abstract void handlerException(ValidateException e);
    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public void run(){
        if(request == null){
            BaseResult.addError(errorMsg,"request不能为空");
        }
        try {
            validate();
        }catch (ValidateException e){
            handlerException(e);
        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException(e.getMessage());
        }

    }


    protected void validateRequireString(String field, String errKey, String errMsg){
        String para = getPara(field);
        boolean notBlank = StringKit.isNotBlank(para);
        if(!notBlank){
            addError(errKey,errMsg);
        }
    }

    protected void addError(String errKey,String errMsg){
        BaseResult.addError(errKey,errMsg);
    }

    protected String getPara(String param){
        String parameter = request.getParameter(param);
        return parameter;
    }

    /**
     *
     * @param param
     * @return
     */
    protected String getParaToString(String param){
        String para = getPara(param);
        boolean notBlank = StringKit.isNotBlank(para);
        if(!notBlank){
            addError(errorMsg,para+"不存在");
        }
        return para;
    }



}
